package com.xgs.quartz.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xgs.common.utils.DateUtils;
import com.xgs.common.utils.sign.Md5Utils;
import com.xgs.system.domain.BasicVersion;
import com.xgs.system.domain.Lane;
import com.xgs.system.domain.RosterHistory;
import com.xgs.system.service.BasicVersionService;
import com.xgs.system.service.LaneService;
import com.xgs.system.service.RosterHistoryService;
import com.xgs.system.service.RosterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.xgs.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 * 
 * @author xgs
 */
@Slf4j
@Component("ryTask")
public class RyTask
{
    @Autowired
    private BasicVersionService versionService;

    @Autowired
    private RosterHistoryService historyService;

    @Autowired
    private LaneService laneService;

    private static Map<String, Object> queryRes = new HashMap<>();

//    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i)
//    {
//        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
//    }
//
//    public void ryParams(String params)
//    {
//        System.out.println("执行有参方法：" + params);
//    }
//
//    public void ryNoParams()
//    {
//        System.out.println("执行无参方法");
//    }

    /**
     * 定时任务，每小时执行一次, 查询版本状态
     */
    @Transactional
    public void autoPatchRoster() {
        QueryWrapper<BasicVersion> query = Wrappers.query();
        query.in("state", 1,2,4);
        query.select("max(version) as version, id");
        query.groupBy("version", "id");
        List<BasicVersion> infoList = versionService.list(query);
        if (!infoList.isEmpty()) {
            for (BasicVersion info : infoList) {
                if (info != null && !info.getVersion().isEmpty()) {
                    QueryWrapper<RosterHistory> queryWrapper = Wrappers.query();
                    queryWrapper.le("version", info.getVersion());
                    queryWrapper.in("spare3", 0,3,4);
                    queryWrapper.eq("del_flag", 0);
                    queryWrapper.apply("end_date >= TO_TIMESTAMP({0}, 'YYYY-MM-DD HH24:MI:SS')", DateUtils.getTime());
                    List<RosterHistory> list = historyService.list(queryWrapper);
                    if (!list.isEmpty()) {
                        Map<String, List<RosterHistory>> groupedByStation = list.stream().collect(Collectors.groupingBy(RosterHistory::getExStationId));
                        groupedByStation.forEach((stationId, dataModels) -> getIssuedState(info.getVersion(), stationId, dataModels));
                        if (queryRes.get("code") == "ok") {
                            BasicVersion basic = new BasicVersion();
                            basic.setId(info.getId());
                            basic.setState(3);
                            basic.setCollectTime(new Date());
                            basic.setUpdateTime(DateUtils.getNowDate());
                            versionService.updateById(basic);
                        }
                    }
                }
            }
        }
    }

    private void getIssuedState(String version, String stationId, List<RosterHistory> dataModels) {
        RestTemplate restTemplate = new RestTemplate();
        JSONObject json = new JSONObject();
        json.put("version", version);

        String fileName = "state_01_differtollvehicle_" + DateUtils.dateTimeNow() + ".json";
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json; charset=utf-8");
        headers.set("Accept-Charset", "utf-8");
        headers.add("user", "lane");
        headers.add("pass", Md5Utils.EncryptEx("Xgssoft", true, "xgs", false));
        headers.add("md5", Md5Utils.hash(json.toString()));
        headers.add("filename", fileName);
        log.info("版本号：{}查询下发状态json：{}，查询时间：{}", version, json, DateUtils.getTime());
        HttpEntity<String> request = new HttpEntity<>(json.toString(), headers);

        QueryWrapper<Lane> query = Wrappers.query();
        query.eq("id", stationId);
        query.select("ip");
        Lane info = laneService.getOne(query);
        String url = info.getIp() + fileName;
        try {
            ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
            JSONObject jsonResult = JSON.parseObject(response.getBody());
            if (jsonResult.getInteger("code") != 200) {
                log.error("版本号：{}查询下发状态结果异常：{}", version, jsonResult.getString("Msg"));
                queryRes.put("code", "fail");
                QueryWrapper<RosterHistory> qu = new QueryWrapper<>();
                qu.eq("version", version);
                qu.eq("ex_station_id", stationId);
                qu.eq("del_flag", 0);
                RosterHistory en = new RosterHistory();
                en.setSpare3(4);
                historyService.update(en, qu);
            } else {
                queryRes.put("code", "ok");
                QueryWrapper<RosterHistory> qu = new QueryWrapper<>();
                qu.eq("version", version);
                qu.eq("del_flag", 0);
                qu.eq("ex_station_id", stationId);
                RosterHistory en = new RosterHistory();
                en.setSpare3(3);
                historyService.update(en, qu);
            }
        } catch (RuntimeException e) {
            queryRes.put("code", "fail");
        }
    }
}
